package structure

import (
	"fmt"

	"gddgame.cc/galaxy/utils"
	"gddgame.cc/galaxy/utils/serialize"
)

type EventStruct struct {
}

func (execute *Execute) BindEvent(conn SafeConn, data Data, event byte, mode EventMode, b []byte) *EventData {
	//先添加
	e := execute.GenerateEvent(event, mode, b)
	slot := serialize.GetSlot()
	info := map[string]interface{}{
		GetEventKey(event): GenerateEventData(e, slot),
	}
	conn.AutoRelease(slot)
	execute.Update(conn, data, info)
	return e
}

func (execute *Execute) GenerateEvent(event byte, mode EventMode, b []byte) *EventData {
	//先添加
	e := &EventData{
		Mode:    mode,
		Content: b,
		Event:   event,
	}
	return e
}

func (execute *Execute) ClearEvent(conn SafeConn, data Data, event byte) {
	props := []string{GetEventKey(event)}
	execute.DelProps(conn, data, props)
}

func GetEventKey(event byte) string {
	return EventDataType + utils.ToString(event)
}

func GetEventData(b []byte) *EventData {
	if b == nil || len(b) == 0 {
		return nil
	}
	e := &EventData{}
	_, err := e.UnmarshalMsg(b)
	if err != nil {
		fmt.Println("get event", err)
	}

	return e
}

func GenerateEventData(event *EventData, slot serialize.Slot) []byte {
	if slot != nil {
		_ = slot.Set(event)
		return slot.Bytes()
	}
	b, err := event.MarshalMsg(nil)
	if err != nil {
		fmt.Println("bind event", err)
	}
	return b
}

func (execute *Execute) GetEvent(conn SafeConn, data Data, event byte) *EventData {
	v := execute.GetProp(conn, data, GetEventKey(event))
	if v == nil {
		return nil
	}
	return GetEventData(utils.ToBytes(v))
}

func (execute *Execute) GetEvents(conn SafeConn, data Data, events []byte) []*EventData {
	props := make([]string, len(events))
	for i, event := range events {
		props[i] = GetEventKey(event)
	}
	es := make([]*EventData, len(events))
	vs := execute.GetProps(conn, data, props)
	for i, prop := range props {
		v := vs[prop]
		es[i] = GetEventData(utils.ToBytes(v))
	}
	return es
}
